package cn.piesat.client.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Timer;
import java.util.TimerTask;

public class ProcCmd {

    private Logger logger = LoggerFactory.getLogger(ProcCmd.class);

    private static final String OS_WINDOWS = "windows";
    private String charsetName = "UTF-8";
    private Long timeout = (long) (1000*60*120);
    private boolean isSuccess=true;

    public Long getTimeout() {
        return timeout;
    }

    public void setTimeout(Long timeout) {
        this.timeout = timeout;
    }
    public String getCharsetName() {
        return charsetName;
    }

    public void setCharsetName(String charsetName) {
        this.charsetName = charsetName;
    }

    public boolean exec(String commandstr) {
        try {
            String osName = System.getProperty("os.name");
            //判断是windows
            if (osName.toLowerCase().startsWith(OS_WINDOWS)) {
                commandstr = String.format("cmd.exe /c %s", commandstr);
            }
            logger.info("执行算法命令:{}",commandstr);
            final Process pr = Runtime.getRuntime().exec(commandstr);
            new Thread(() -> {
                BufferedReader br_in = null;
                InputStreamReader inputStreamReader = null;
                try{
                    inputStreamReader = new InputStreamReader(pr.getInputStream(), StandardCharsets.UTF_8);
                    br_in = new BufferedReader(inputStreamReader);
                    String buff = null;
                    while ((buff = br_in.readLine()) != null) {
                        logger.info(buff);
                        try {
                            Thread.sleep(100);
                        } catch (Exception e) {
                        }
                    }
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }finally {
                    if(br_in!=null){
                        try {
                            br_in.close();
                        } catch (IOException e) {
                            logger.error(e.getMessage());
                        }
                    }
                    if(inputStreamReader!=null){
                        try {
                            inputStreamReader.close();
                        } catch (IOException e) {
                            logger.error(e.getMessage());
                        }
                    }
                }
            }).start();
            new Thread(() -> {
                BufferedReader brErr = null;
                InputStreamReader inputStreamReader = null;
                try{
                    inputStreamReader = new InputStreamReader(pr.getErrorStream(), StandardCharsets.UTF_8);
                    brErr = new BufferedReader(inputStreamReader);
                    String buff;
                    while ((buff = brErr.readLine()) != null) {
                        try {
                            logger.error(buff);
                            Thread.sleep(100);
                        } catch (Exception e) {
                        }
                    }
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }finally {
                    if(brErr!=null){
                        try {
                            brErr.close();
                        } catch (IOException e) {
                            logger.error(e.getMessage());
                        }
                    }
                    if(inputStreamReader!=null){
                        try {
                            inputStreamReader.close();
                        } catch (IOException e) {
                            logger.error(e.getMessage());
                        }
                    }
                }
            }).start();
            //阻塞线程,等待命令执行完毕
            pr.waitFor();
            pr.destroy();
            return true;
        } catch (Exception e) {
            logger.error("算法命令执行失败:{}",e.getMessage());
            return false;
        }
    }
    private static class Worker extends Thread {
        private final Process process;
        private Integer exit;

        private Worker(Process process) {
            this.process = process;
        }

        public void run() {
            try {
                exit = process.waitFor();
            } catch (InterruptedException ignore) {
                return;
            }
        }
    }
    public boolean execByTimeoutShell(String commandstr){
        Runtime runtime = Runtime.getRuntime();
        Process process = null;
        try {
            if(commandstr.contains("|"))
            {
                String[] sh = new String[]{"/bin/sh", "-c", commandstr};
                process = runtime.exec(sh);
            }else
            {
                process = runtime.exec(commandstr);
            }
            outputLog(process, true, true);

            Worker worker = new Worker(process);
            worker.start();
            worker.join(this.timeout);

            if (worker.exit != null){
                if(isSuccess){
                    logger.info("Process out :执行成功..." );
                }
                else {
                    logger.info("Process out :执行过程中有错误发生..." );
                }
                return isSuccess;
            }else{
                logger.info("Process err :执行超时：" + commandstr );
                //超时
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if(process!= null){
                process.destroy();
            }
        }

        return false;
    }
    private void outputLog(final Process pr, boolean printOutput, boolean printError) {
        if(printOutput){
            new Timer().schedule(new TimerTask(){

                @Override
                public void run() {

                    BufferedReader br_in = null;
                    try {
                        br_in = new BufferedReader(new InputStreamReader(pr.getInputStream(),charsetName));
                        String buff = null;
                        String lastBuff = null;
                        while ((buff = br_in.readLine()) != null) {

                            if(buff != null && !buff.equals(lastBuff)){
                                lastBuff = buff;
                                logger.info("Process out :" + buff);
                            }

                            try {Thread.sleep(100); } catch(Exception e) {}
                        }
                        br_in.close();
                    } catch (IOException ioe) {
                        logger.error("Exception caught printing process printOutput.");
                        //ioe.printStackTrace();
                    } finally {
                        try {
                            br_in.close();
                        } catch (Exception ex) {}
                    }

                }

            }, 100);
        }

        if(printError){
            new Timer().schedule(new TimerTask(){

                @Override
                public void run() {
                    BufferedReader br_err = null;

                    try {
                        br_err = new BufferedReader(new InputStreamReader(pr.getErrorStream(), charsetName));
                        String buff = null;
                        String lastBuff = null;
                        while ((buff = br_err.readLine()) != null) {

                            if(buff != null && !buff.equals(lastBuff)){
                                lastBuff = buff;
                                logger.info("Process err :" + buff);
                                //isSuccess=false;
                                //break;
                            }
                            try {Thread.sleep(100); } catch(Exception e) {}

                        }
                        br_err.close();
                    } catch (IOException ioe) {
                        System.out.println("Exception caught printing process printError.");
                        //ioe.printStackTrace();
                    } finally {
                        try {
                            br_err.close();
                        } catch (Exception ex) {}
                    }
                }

            }, 100);
        }
    }
}
